// mircoApp/ai-digital-human/aiChatWindow/aiChatWindow.js
const app = getApp();
let countNum = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    chatList: [],
    memberInfo: {},
    messageId: "",
    // 发送状态
    sendStatus: false,
    rollInterval: null, // 用于存储轮询的定时器
    msgText: "",
    ai_avatar: "",
    iPhoneBottom: false,
    xf_open: false,
    audioChild: null, //音频播放对象
    audioStatus: false,
    page: 1,
    last_page: "",

    timeout_reconnect: null,
    timeoutOpen: null,
    timeoutPong: null,
    heartBeatInterval: null,
    websock: null,
    isClosed: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initWebSocket();
    let val = wx.getStorageSync('iPhoneBottom');
    if (val) {
      this.setData({
        iPhoneBottom: true
      })
    }
    this.init();
  },
  sendMsg() {
    this.setData({
      sendStatus: true
    })
    this.sendMsgPost();
  },

  async init() {
    this.setData({
      page: 1,
      last_page: 0,
      chatList: []
    })
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("plugin.ai-digital-human.frontend.controllers.chat.index"),
    })
    if (data.result) {
      this.setData({
        messageId: data.data.id,
        ai_avatar: data.data.ai_avatar,
        memberInfo: data.data.member_info,
        xf_open: data.data.xf_open == 1 ? true : false,
      })
      this.historyGet();
    } else {
      app.tips(data.msg)
    }
  },
  async historyGet(key = 'first') {
    if (key == 'more') {
      if (this.data.page >= this.data.last_page) {
        app.tips('没有更多了')
        wx.stopPullDownRefresh();
        return
      }
      this.setData({
        page: this.data.page + 1
      })
    }
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("plugin.ai-digital-human.frontend.controllers.chat.chats"),
      data: {
        chat_id: this.data.messageId,
        page: this.data.page
      }
    })
    if (data.result) {
      let array = data.data.list.data
      for (let i = 0; i < array.length; i++) {
        await this.loadSetList(array[i].id, array[i].content, array[i].member_id ? 0 : 1, array[i].msg_type);
      }
      this.setData({
        last_page: data.data.list.last_page
      })
      if (key == 'first') {
        setTimeout(() => {
          this.scrollToBottom();
        }, 1000);
      } else {
        setTimeout(() => {
          this.scrollToTop();
        }, 1000);
        wx.stopPullDownRefresh();
      }
    } else {
      app.tips(msg)
    }
  },
  scrollToTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0 // 滚动动画持续时间，设为0表示立即滚动
    })
  },
  loadSetList(id, content, directionType, msg_type, infoDetail) {
    this.data.chatList.unshift({
      id,
      content,
      direction_type: directionType,
      msg_type,
      infoDetail
    });
    this.setData({
      chatList: this.data.chatList
    })
  },
  async sendMsgPost() {
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("plugin.ai-digital-human.frontend.controllers.chat.send-message"),
      data: {
        id: this.data.messageId,
        message: this.data.msgText
      },
    })
    if (data.result) {
      this.addMessageToChatList(data.data.id, this.data.msgText, 0, 0)
      this.setData({
        msgText: "",
      })
    } else {
      this.setData({
        sendStatus: false
      })
      app.tips(data.msg);
    }
  },
  scrollToBottom() {
    const query = wx.createSelectorQuery()
    query.select('.chat-scroll').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      // 获取聊天窗口的高度
      const chatWindowHeight = res[0].height
      wx.pageScrollTo({
        scrollTop: chatWindowHeight,
        duration: 0 // 滚动动画持续时间，设为0表示立即滚动
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.audioClearn();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.audioClearn();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.historyGet('more')
  },
  audioClearn() {
    if (this.data.audioChild) {
      this.data.audioChild.destroy();
    }
    this.data.isClosed = true;
    this.clearMethod();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  addMessageToChatList(id, content, direction_type, msg_type, infoDetail) {
    let obj = {
      id: id,
      content: content,
      direction_type: direction_type,
      msg_type
    }
    if (infoDetail && infoDetail.msg_type == 0) {
      if (infoDetail.begin) {
        this.setData({
          sendStatus: true
        })
      }
      if (infoDetail.end) {
        this.setData({
          sendStatus: false
        })
      }
      const index = this.data.chatList.findIndex((item) => item.id == id && item.direction_type == 1);
      if (index !== -1) {
        // this.data.chatList[index].content += obj.content
        this.setData({
          ['chatList[' + index + '].content']: this.data.chatList[index].content += obj.content,
        })
      } else {
        this.sendStatus = false;
        this.setData({
          ['chatList[' + this.data.chatList.length + ']']: obj,
        })
      }
      return
    }
    this.setData({
      ['chatList[' + this.data.chatList.length + ']']: obj,
    })
    this.scrollToBottom();
  },

  // 音频组件 start
  closeLoad() {
    this.setData({
      audioStatus: false
    })
  },
  showLoad() {
    this.setData({
      audioStatus: true
    })
  },
  tap_Audio(e) {
    if (this.data.audioChild) {
      this.data.audioChild.pause();
      this.data.audioChild = null;
    }
    this.data.audioChild = wx.createInnerAudioContext({
      useWebAudioImplement: false,
    });
    this.data.audioChild.src = e.detail;
    this.data.audioChild.play();
    this.data.audioChild.onPlay(() => {});
    this.data.audioChild.onEnded(() => {});
    this.data.audioChild.onError((res) => {
      console.error("播放音频时出错:", res.errMsg, res.errCode);
      app.tips("播放音频时出错:" + res.errMsg)
    });
  },
  // 音频组件 end

  // wss start
  initWebSocket() {
    let cleanedUrl = app.data.host.replace(/^(http:\/\/|https:\/\/)/, '');
    console.log(cleanedUrl, 'cleanedUrl')
    this.data.websock = wx.connectSocket({
      url: `wss://${cleanedUrl}/ws`,
    });
    this.data.websock.onMessage((e) => {
      this.websocketonmessage(e);
    });
    this.data.websock.onOpen(() => {
      this.websocketonopen();
    });
    this.data.websock.onError((e) => {
      this.websocketonerror(e);
    });
    this.data.websock.onClose((e) => {
      this.websocketclose(e);
    });
  },
  websocketonmessage(e) {
    if (e.data == 'pong') return
    let infoDetail = JSON.parse(e.data);
    if (infoDetail.message) {
      if (infoDetail.msg_type == 0) {
        this.addMessageToChatList(infoDetail.msg_id, infoDetail.message, 1, 0, infoDetail);
      } else if (infoDetail.msg_type == 1) {
        this.addMessageToChatList(null, infoDetail.message, 1, infoDetail.msg_type);
      }
    }
  },
  websocketonopen() {
    this.heartBeatStart();
  },
  heartBeatStart() {
    this.data.timeoutOpen && clearTimeout(this.data.timeoutOpen);
    this.data.timeoutOpen = setTimeout(() => {
      //这里发送一个心跳，后端收到后，返回一个心跳消息，
      if (this.data.websock.readyState == 1) {
        this.data.websock.send({
          data: JSON.stringify({
            type: "register",
            data: {
              group: "ai_digital_human"
            }
          })
        });
        this.data.websock.send({
          data: JSON.stringify({
            type: "login",
            data: {
              session_id: wx.getStorageSync('wx_token'),
              group: "ai_digital_human"
            }
          })
        });
        this.keepHeartBeat();
      } else {
        //否则重连
        this.reconnect();
      }
    }, 1000);
  },
  reconnect() {
    if (this.data.isClosed) {
      return;
    }
    this.data.websock.close();
    this.data.websock = null;
    this.data.timeout_reconnect && clearTimeout(this.data.timeout_reconnect);
    this.data.timeout_reconnect = setTimeout(() => {
      //新连接
      this.initWebSocket();
    }, 5000);
  },
  keepHeartBeat() {
    if (!this.data.websock) return
    this.data.heartBeatInterval = setInterval(() => {
      // 每隔一分钟发送一个心跳包消息
      this.data.websock.send({
        data: JSON.stringify({
          type: "ping"
        })
      });
    }, 5000);
  },
  websocketclose() {
    this.clearMethod();
    if (!this.data.isClosed) {
      this.reconnect();
    }
  },
  websocketonerror() {
    this.clearMethod();
    if (!this.data.isClosed) {
      this.reconnect();
    }
  },
  clearMethod() {
    if (this.data.websock) {
      this.data.websock.close();
    }
    if (this.data.timeout_reconnect) {
      this.data.timeout_reconnect = null;
      clearInterval(this.data.timeout_reconnect);
    }
    if (this.data.timeoutOpen) {
      this.data.timeoutOpen = null;
      clearInterval(this.data.timeoutOpen);
    }
    if (this.data.timeoutPong) {
      this.data.timeoutPong = null;
      clearInterval(this.data.timeoutPong);
    }
    if (this.data.heartBeatInterval) {
      this.data.heartBeatInterval = null;
      clearInterval(this.data.heartBeatInterval);
    }
    if (this.data.audioChild) {
      this.data.audioChild.removeEventListener("ended");
      this.data.audioChild.removeEventListener("canplaythrough");
      this.data.audioChild.pause();
      this.data.audioChild = null;
    }
  },
  // wss end
})